package com.edu.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Author ZCN
 * @Date 2021/11/14 17:19
 * @Version 1.0
 **/
// 解析文件工具类
public class FileParse {

    public static String filestorg(HttpServletRequest request) throws IOException, ServletException {
        // 转换请求对象得到文件对象
        Part part = request.getPart("file");
        String disposition = part.getHeader("Content-Disposition");
        String suffix = disposition.substring(disposition.lastIndexOf("."),disposition.length()-1);
        //随机的生存一个32的字符串(保存文件名)
        String filename = UUID.randomUUID()+suffix;

        String realPath = request.getServletContext().getRealPath("upload");

//        System.out.println(realPath);
        //  获得文档保存目录
        File dirvm = new File(realPath);
        File parentFile = dirvm.getParentFile().getParentFile();
//        System.out.println(parentFile.toString()+"\\upload");
        File dir = new File(parentFile.toString() + "\\upload");
        if (!dir.exists()) {
            System.out.println("文件目录创建中。。。");
            dir.mkdirs();
        }

        // 开始把内存中的数据写到图片中
        InputStream is = part.getInputStream();
        FileOutputStream fos = new FileOutputStream(parentFile.toString() + "\\upload"+"/"+filename);
        byte[] bty = new byte[1024];
        int length =0;
        while((length=is.read(bty))!=-1){
            fos.write(bty,0,length);
        }
        fos.close();
        is.close();
        return "/photo/"+filename;
    }
}
